﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Security;
using System.Text;
using System.Threading.Tasks;

namespace Mojito.Utils
{
    public class HttpContentTypeEnum
    {
        public const string FORM = "multipart/form-data";
        public const string URLCODED = "application/x-www-form-urlencoded";
        public const string JSON = "application/json";
        public const string TEXT = "application/text";
        public const string XML = "application/xml";
    }


    public class HttpUtil
    {
        /// <summary>
        ///  Http 请求默认编码
        /// </summary>
        private static readonly Encoding DefaultEncoding = Encoding.UTF8;
        // 
        private static readonly RemoteCertificateValidationCallback _remoteCertificateValidationCallback =
            new RemoteCertificateValidationCallback((sender, certificate, chain, errors) => errors == SslPolicyErrors.None);

        #region HttpClient

        /// <summary>
        ///  Get
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> GetAsync(string uri, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();
            client.Timeout = System.TimeSpan.FromSeconds(20);
            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value.ToString());
            }
            return await client.GetAsync(uri);
        }

        /// <summary>
        ///  Post
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="param"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> PostAsync(string uri, string param, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();
            client.Timeout = System.TimeSpan.FromSeconds(20);
            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value);
            }

            try
            {
                HttpContent content = null;
                if (header != null && header.ContainsKey("Content-Type"))
                {
                    switch (header["Content-Type"])
                    {
                        case HttpContentTypeEnum.FORM:
                            content = new MultipartFormDataContent(param);
                            break;
                        case HttpContentTypeEnum.URLCODED:
                            var paramDict = new Dictionary<string, string>();
                            var urlencoded = param.Split("&");
                            foreach (var _par in urlencoded)
                            {
                                var keyValue = _par.Split("=");
                                paramDict.Add(keyValue[0], keyValue[1]);
                            }
                            content = new FormUrlEncodedContent(paramDict);
                            break;
                        case HttpContentTypeEnum.JSON:
                        case HttpContentTypeEnum.TEXT:
                        case HttpContentTypeEnum.XML:
                            content = new StringContent(param, Encoding.UTF8, header["Content-Type"]);
                            break;
                        default: break;
                    }
                }
                return await client.PostAsync(uri, content);
            }
            catch(System.Threading.Tasks.TaskCanceledException ex)
            {
                throw new ApplicationException("请求超时");
            }
        }

        /// <summary>
        ///  Post
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="param"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> PostAsync(string uri, IDictionary<string, string> param, IDictionary<string, string> header = null)
        {
            HttpClient client = new HttpClient();

            if (header != null && header.Count > 0)
            {
                foreach (var head in header)
                    client.DefaultRequestHeaders.TryAddWithoutValidation(head.Key, head.Value);
            }

            HttpContent content = new FormUrlEncodedContent(param);
            return await client.PostAsync(uri, content);
        }

        /// <summary>
        ///  Post
        /// </summary>
        /// <param name="uri"></param>
        /// <param name="param"></param>
        /// <param name="header"></param>
        /// <returns></returns>
        public static async Task<string> PostAsync(string uri, byte[] param, IDictionary<string, string> header = null)
        {
            //HttpClient client = new HttpClient();
            //if (header != null && header.Count > 0)
            //{
            //    foreach (var head in header)
            //        client.DefaultRequestHeaders.Add(head.Key, head.Value.ToString());
            //}
            //StreamContent content = new StreamContent(param);
            //var response = await client.PostAsync(uri, content);
            //return await response.Content.ReadAsStringAsync();
            return null;
        }

        #endregion
    }
}
